<template>
  <el-dialog
    v-model="dialogVisible"
    title="选择 BOM"
    width="60%"
    :destroy-on-close="true"
  >
    <el-table
      :data="bomList"
      row-key="id"
      border
      highlight-current-row
      :current-row-key="currentSelection?.id"
      @row-click="onRowClick"
      style="width: 100%; max-height: 400px; overflow: auto;"
    >
      <el-table-column
        prop="id"
        label="BOM 编号"
        width="120"
      />
      <el-table-column
        prop="name"
        label="BOM 名称"
      />
    </el-table>

    <template #footer>
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onConfirm">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { BOM } from '@/types/basic/BOM'
import request from '@/util/request'
// 接收父组件 v-model:modelValue（即 bomId）和 v-model:visible
const props = defineProps<{
  modelValue: number  // 只传回选中的 BOM id
  visible: boolean
}>()
const emit = defineEmits<{
  (e: 'update:modelValue', value: number): void
  (e: 'update:visible', value: boolean): void
}>()

// 控制弹窗显示
const dialogVisible = computed({
  get: () => props.visible,
  set: val => emit('update:visible', val)
})

// BOM 列表
const bomList = ref<BOM[]>([])

// 当前选中行
const currentSelection = ref<BOM | null>(null)

// 加载所有 BOM
async function loadBOMs() {
  try {
    const resp = await request.post('basic/BOM/getAllBOM')
    bomList.value = Array.isArray(resp.data.data) ? resp.data.data : []
  } catch {
    ElMessage.error('BOM 加载失败，请稍后重试')
  }
}

onMounted(loadBOMs)

// 初始化外部选中
watch(
  () => props.modelValue,
  id => {
    currentSelection.value = bomList.value.find(b => b.id === id) || null
  }
)

// 点击行选中
function onRowClick(row: BOM) {
  currentSelection.value = row
}

// 取消
function onCancel() {
  emit('update:visible', false)
}

// 确认：如果选中了才返回 id
function onConfirm() {
  if (!currentSelection.value) {
    ElMessage.warning('请先选择一个 BOM')
    return
  }
  emit('update:modelValue', currentSelection.value.id)
  emit('update:visible', false)
}
</script>

<style scoped>
/* 如需调整表格或弹窗样式，可在此添加 */
</style>
